import qqmap from '../lib/qqmap-wx-jssdk.min.js';
const wxqqmap = new qqmap({
  key: 'DVPBZ-IF3H4-6WJUN-XFNWE-CVM2S-UFFY6'
});
//获取距顶部坐标的位置
export let domInter = (value, _this) => { 
  return new Promise((resolve, reject) => {
    var query = wx.createSelectorQuery().in(_this)
    query.select(value).boundingClientRect(function(res) {
      resolve(res)
    }).exec()
  })
}

export function getCurrentAddress(options) {
  const {
    success
  } = options;
  wx.getLocation({
    type: "gcj02",
    success: function(res) {
      let location = {
        latitude: res.latitude,
        longitude: res.longitude
      }
      getAddress({
        location,
        success(data) {
        success&&success(data);
        }
      });
    }
  });

}

export function getCurrentAddressList(options) {
  const {
    success
  } = options;
  wx.getLocation({
    type: "gcj02",
    success: function(res) {
      let addressList = [];
      let location = {
        latitude: res.latitude,
        longitude: res.longitude
      }
      getPois({
        location,
        success(pois) {
          let addrs = [];
          pois.forEach(poi => {
            const {
              title,
              location,
              address,
              ad_info
            } = poi;
            addrs.push(Object.assign({
              title,
              location,
              address
            }, resolveAdInfo(ad_info)));
          });
          success && success(addrs);
        }
      });
    },
  })
}

function resolveAdInfo(adinfo) {
  const {
    city,
    district,
    adcode
  } = adinfo;
  return {
    city,
    district,
    district_id: adcode,
    city_id: adcode.replace(/\d{2}$/, '00')
  }
}
export function getPois(options) {
  const {
    location,
    success
  } = options;
  wxqqmap.reverseGeocoder({
    location,
    get_poi: 1,
    poi_options: "policy=2",
    success(res) {
      success && success(res.result.pois)
    },
    fail: function(err) {
      console.log(err)
    }
  });
}
export function getAddress(options) {
  const {
    location,
    success
  } = options;
  wxqqmap.reverseGeocoder({
    location,
    get_poi: 1,
    // poi_options: "policy=2",
    success(res) {
       console.log(res);
      success && success({name:res.result.address_component
        .district + res.result.address_component.street, location: res.result.location})
    },
    fail: function(err) {
      console.log(err)
    }
  });
}